package com.spzx.product;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.spzx.product.domain.Category;
import com.spzx.product.service.CategoryService;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * projectName: spzx-parent
 *
 * @author: 比丢比丢
 * time: 2024/7/9 20:54 周二
 * description:
 */
//创建监听器
public class ExcelCategoryListener <CategoryExcelVo> extends AnalysisEventListener<com.spzx.product.domain.CategoryExcelVo> {

    //使用分类service
    //构造传递
    private CategoryService categoryService;
    public ExcelCategoryListener(CategoryService categoryService){
        this.categoryService = categoryService;
    }

    private static final int BATCH_COUNT = 100;

    //缓存的数据
    private List<com.spzx.product.domain.CategoryExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(com.spzx.product.domain.CategoryExcelVo categoryExcelVo, AnalysisContext analysisContext) {
        cachedDataList.add(categoryExcelVo);
        if (cachedDataList.size() >= BATCH_COUNT){
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }




    //批量添加数据库
    private void saveData(){
        //List<CategoryExcelVo> -- List<Category>
        List<Category> list = cachedDataList.stream().map(categoryExcelVo -> {
            Category category = new Category();
            BeanUtils.copyProperties(categoryExcelVo, category);
            return category;
        }).collect(Collectors.toList());

        categoryService.saveBatch(list);
    }



    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }
}
